import { ref, computed, onMounted, onUnmounted } from 'vue'
import { 
  performanceIntegrationService,
  dataLoaderService,
  renderOptimizationService,
  memoryManagementService,
  dumpCacheService
} from '../services'
import { LoadPriority } from '../services/dataLoaderService'
import type { 
  PerformanceMetrics, 
  MemoryStats, 
  DumpCacheStats,
  OptimizationStatus 
} from '../services'

/**
 * 性能优化组合式函数
 * 为Vue组件提供性能优化功能的便捷接口
 */
export function usePerformanceOptimization() {
  // 响应式状态
  const isInitialized = ref(false)
  const isOptimizing = ref(false)
  const performanceMetrics = ref<PerformanceMetrics | null>(null)
  const memoryStats = ref<MemoryStats | null>(null)
  const optimizationStatus = ref<OptimizationStatus | null>(null)
  const errors = ref<string[]>([])

  // 计算属性
  const isPerformanceGood = computed(() => {
    if (!performanceMetrics.value) return null
    const metrics = performanceMetrics.value
    return (
      metrics.firstContentfulPaint < 2000 &&
      metrics.largestContentfulPaint < 4000 &&
      metrics.cumulativeLayoutShift < 0.1 &&
      metrics.memoryUsage < 512 // 512MB
    )
  })

  const memoryUsageLevel = computed(() => {
    if (!memoryStats.value) return 'unknown'
    const usage = memoryStats.value.totalUsed
    if (usage < 256) return 'low'
    if (usage < 512) return 'normal'
    if (usage < 1024) return 'high'
    return 'critical'
  })

  const cacheEfficiency = computed(() => {
    if (!performanceMetrics.value) return 0
    return performanceMetrics.value.cacheHitRate
  })

  // 初始化性能优化
  const initialize = async (config?: {
    enableCaching?: boolean
    enableMemoryManagement?: boolean
    enablePreloading?: boolean
    memoryThresholds?: {
      warning: number
      critical: number
      maximum: number
    }
  }) => {
    try {
      await performanceIntegrationService.initialize(config)
      isInitialized.value = true
      await updateStats()
    } catch (error) {
      const errorMsg = `初始化失败: ${error}`
      errors.value.push(errorMsg)
      console.error('[usePerformanceOptimization]', errorMsg)
    }
  }

  // 优化工作区
  const optimizeWorkspace = async (workspaceId: string) => {
    if (!isInitialized.value) {
      await initialize()
    }

    isOptimizing.value = true
    try {
      await performanceIntegrationService.optimizeWorkspace(workspaceId)
      await updateStats()
    } catch (error) {
      const errorMsg = `工作区优化失败: ${error}`
      errors.value.push(errorMsg)
      console.error('[usePerformanceOptimization]', errorMsg)
    } finally {
      isOptimizing.value = false
    }
  }

  // 预加载数据
  const preloadData = async (workspaceId: string) => {
    try {
      await performanceIntegrationService.preloadWorkspaceData(workspaceId)
    } catch (error) {
      const errorMsg = `数据预加载失败: ${error}`
      errors.value.push(errorMsg)
      console.error('[usePerformanceOptimization]', errorMsg)
    }
  }

  // 启动分阶段渲染
  const startPhaseRendering = async (workspaceId: string) => {
    try {
      await renderOptimizationService.startPhaseRendering(workspaceId)
    } catch (error) {
      const errorMsg = `分阶段渲染启动失败: ${error}`
      errors.value.push(errorMsg)
      console.error('[usePerformanceOptimization]', errorMsg)
    }
  }

  // 清理缓存
  const clearCache = (workspaceId?: string) => {
    try {
      if (workspaceId) {
        performanceIntegrationService.clearWorkspaceCache(workspaceId)
      } else {
        // 清理所有缓存
        memoryManagementService.performSmartCleanup()
      }
    } catch (error) {
      const errorMsg = `缓存清理失败: ${error}`
      errors.value.push(errorMsg)
      console.error('[usePerformanceOptimization]', errorMsg)
    }
  }

  // 更新统计信息
  const updateStats = async () => {
    try {
      const [perfStats, memStats, optStatus] = await Promise.allSettled([
        Promise.resolve(performanceIntegrationService.getPerformanceStats()),
        performanceIntegrationService.getMemoryStats(),
        Promise.resolve(performanceIntegrationService.getServiceStatus())
      ])

      if (perfStats.status === 'fulfilled') {
        performanceMetrics.value = perfStats.value.performance
      }

      if (memStats.status === 'fulfilled') {
        memoryStats.value = memStats.value
      }

      if (optStatus.status === 'fulfilled') {
        optimizationStatus.value = optStatus.value.optimizationStatus
      }
    } catch (error) {
      console.error('[usePerformanceOptimization] 更新统计信息失败:', error)
    }
  }

  // 生成性能报告
  const generateReport = async () => {
    try {
      return await performanceIntegrationService.generatePerformanceReport()
    } catch (error) {
      const errorMsg = `生成性能报告失败: ${error}`
      errors.value.push(errorMsg)
      console.error('[usePerformanceOptimization]', errorMsg)
      return null
    }
  }

  // 清除错误
  const clearErrors = () => {
    errors.value = []
  }

  // 生命周期钩子
  onMounted(() => {
    // 自动初始化
    initialize()
    
    // 定期更新统计信息
    const statsInterval = setInterval(updateStats, 30000) // 30秒
    
    onUnmounted(() => {
      clearInterval(statsInterval)
    })
  })

  return {
    // 状态
    isInitialized,
    isOptimizing,
    performanceMetrics,
    memoryStats,
    optimizationStatus,
    errors,
    
    // 计算属性
    isPerformanceGood,
    memoryUsageLevel,
    cacheEfficiency,
    
    // 方法
    initialize,
    optimizeWorkspace,
    preloadData,
    startPhaseRendering,
    clearCache,
    updateStats,
    generateReport,
    clearErrors
  }
}

/**
 * 数据加载组合式函数
 * 专门用于数据加载和缓存管理
 */
export function useDataLoader() {
  const isLoading = ref(false)
  const loadingProgress = ref(0)
  const loadedData = ref<Map<string, any>>(new Map())

  // 加载日志数据
  const loadLogData = async (workspaceId: string, logType: string, priority: LoadPriority = LoadPriority.NORMAL) => {
    const cacheKey = `${workspaceId}_${logType}`
    
    if (loadedData.value.has(cacheKey)) {
      return loadedData.value.get(cacheKey)
    }

    isLoading.value = true
    try {
      const data = await dataLoaderService.loadLogData(workspaceId, logType, priority)
      if (data) {
        loadedData.value.set(cacheKey, data)
      }
      return data
    } finally {
      isLoading.value = false
    }
  }

  // 加载组件日志
  const loadComponentLogs = async (workspaceId: string, componentName: string, priority: LoadPriority = LoadPriority.NORMAL) => {
    const cacheKey = `${workspaceId}_component_${componentName}`
    
    if (loadedData.value.has(cacheKey)) {
      return loadedData.value.get(cacheKey)
    }

    isLoading.value = true
    try {
      const logs = await dataLoaderService.loadComponentLogs(workspaceId, componentName, priority)
      loadedData.value.set(cacheKey, logs)
      return logs
    } finally {
      isLoading.value = false
    }
  }

  // 加载组件列表
  const loadComponentList = async (workspaceId: string, priority: LoadPriority = LoadPriority.NORMAL) => {
    const cacheKey = `${workspaceId}_components`
    
    if (loadedData.value.has(cacheKey)) {
      return loadedData.value.get(cacheKey)
    }

    isLoading.value = true
    try {
      const components = await dataLoaderService.loadComponentList(workspaceId, priority)
      loadedData.value.set(cacheKey, components)
      return components
    } finally {
      isLoading.value = false
    }
  }

  // 清理加载的数据
  const clearLoadedData = (workspaceId?: string) => {
    if (workspaceId) {
      // 清理特定工作区的数据
      const keysToDelete = Array.from(loadedData.value.keys())
        .filter(key => key.startsWith(workspaceId))
      
      keysToDelete.forEach(key => loadedData.value.delete(key))
    } else {
      // 清理所有数据
      loadedData.value.clear()
    }
  }

  return {
    isLoading,
    loadingProgress,
    loadedData: computed(() => loadedData.value),
    loadLogData,
    loadComponentLogs,
    loadComponentList,
    clearLoadedData
  }
}

/**
 * 转储缓存组合式函数
 * 专门用于转储文件的缓存管理
 */
export function useDumpCache() {
  const dumpFiles = ref<Map<string, any[]>>(new Map())
  const dumpStats = ref<DumpCacheStats | null>(null)
  const isScanning = ref(false)

  // 扫描转储文件
  const scanDumpFiles = async (workspaceId: string, forceRefresh: boolean = false) => {
    isScanning.value = true
    try {
      const files = await dumpCacheService.scanDumpFiles(workspaceId, forceRefresh)
      dumpFiles.value.set(workspaceId, files)
      await updateDumpStats(workspaceId)
      return files
    } finally {
      isScanning.value = false
    }
  }

  // 获取转储数据
  const getDumpData = async (workspaceId: string, dumpType: 'framework' | 'operation' | 'app', index: number) => {
    return await dumpCacheService.getDumpData(workspaceId, dumpType, index)
  }

  // 预加载转储数据
  const preloadDumpData = async (workspaceId: string, dumpType: 'framework' | 'operation' | 'app', maxFiles: number = 5) => {
    await dumpCacheService.preloadDumpData(workspaceId, dumpType, maxFiles)
    await updateDumpStats(workspaceId)
  }

  // 更新转储统计
  const updateDumpStats = async (workspaceId?: string) => {
    dumpStats.value = dumpCacheService.getDumpCacheStats(workspaceId)
  }

  // 清理转储缓存
  const clearDumpCache = (workspaceId: string) => {
    dumpCacheService.clearWorkspaceDumpCache(workspaceId)
    dumpFiles.value.delete(workspaceId)
    updateDumpStats()
  }

  // 检查转储数据是否已缓存
  const isDumpDataCached = (workspaceId: string, dumpType: 'framework' | 'operation' | 'app', index: number) => {
    return dumpCacheService.isDumpDataCached(workspaceId, dumpType, index)
  }

  return {
    dumpFiles: computed(() => dumpFiles.value),
    dumpStats,
    isScanning,
    scanDumpFiles,
    getDumpData,
    preloadDumpData,
    updateDumpStats,
    clearDumpCache,
    isDumpDataCached
  }
}

/**
 * 内存管理组合式函数
 * 专门用于内存监控和管理
 */
export function useMemoryManagement() {
  const memoryStats = ref<MemoryStats | null>(null)
  const memoryTrend = ref<'increasing' | 'decreasing' | 'stable'>('stable')
  const isCleaningUp = ref(false)

  // 检查内存使用
  const checkMemoryUsage = async () => {
    memoryStats.value = await memoryManagementService.checkMemoryUsage()
    
    // 更新趋势
    const trend = memoryManagementService.getMemoryTrend(10)
    memoryTrend.value = trend.trend
    
    return memoryStats.value
  }

  // 执行内存清理
  const performCleanup = async () => {
    isCleaningUp.value = true
    try {
      const result = await memoryManagementService.performSmartCleanup()
      await checkMemoryUsage() // 更新统计
      return result
    } finally {
      isCleaningUp.value = false
    }
  }

  // 设置内存阈值
  const setMemoryThresholds = (thresholds: {
    warning?: number
    critical?: number
    maximum?: number
  }) => {
    memoryManagementService.setThresholds(thresholds)
  }

  // 获取内存历史
  const getMemoryHistory = () => {
    return memoryManagementService.getMemoryHistory()
  }

  // 定期检查内存
  const startMemoryMonitoring = (interval: number = 30000) => {
    const timer = setInterval(checkMemoryUsage, interval)
    
    onUnmounted(() => {
      clearInterval(timer)
    })
    
    // 立即执行一次
    checkMemoryUsage()
    
    return timer
  }

  return {
    memoryStats,
    memoryTrend,
    isCleaningUp,
    checkMemoryUsage,
    performCleanup,
    setMemoryThresholds,
    getMemoryHistory,
    startMemoryMonitoring
  }
}